package cn.scw.framework.protocol.tcp;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通道句柄，用来记录通道的状态
 *
 * 由于通道存在连通未验证，联通已验证，以及断开连接等状态
 * 理论上来说，我们只会存储联通的Channel，而已联通未验证则通过的则会在一定规则后彻底断开连接进行移除
 * 句柄是用来包含资源以及附加的信息的容器，可以让我们找到指定的句柄以及对应的附加信息
 */
public class ChannelHandle {

    private static Logger logger= LoggerFactory.getLogger(ChannelHandle.class);
    /**
     * 通道实例
     */
    private Channel channel=null;

    /**
     * 产品编号
     */
    private Integer sensorCode=null;

    /**
     * 是否已经通过验证
     */
    private Boolean isAuthed=false;

    /**
     * 创建通道的时间戳
     */
    private Long startTimestamp=null;


    public void sendMsg(byte[] msg){

        try {
            //判断通道上下文状态是否可用

            ByteBuf encoded = this.channel.alloc().buffer(msg.length);
            encoded.writeBytes(msg);
            channel.writeAndFlush(encoded);
//        channel.writeAndFlush(msg);
//        ByteBuf encoded = channelHandlerContext.alloc().buffer(4 * msg.length());
//        encoded.writeBytes(msg.getBytes());
//        channelHandlerContext.writeAndFlush(encoded);
        }catch (Exception ex){
            logger.info(ex.getMessage());
        }
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }


    public Boolean getIsAuthed() {
        return isAuthed;
    }

    public void setIsAuthed(Boolean isAuthed) {
        this.isAuthed = isAuthed;
    }

    public Long getStartTimestamp() {
        return startTimestamp;
    }

    public void setStartTimestamp(Long startTimestamp) {
        this.startTimestamp = startTimestamp;
    }

    public Integer getSensorCode() {
        return sensorCode;
    }

    public void setSensorCode(Integer sensorCode) {
        this.sensorCode = sensorCode;
    }
}
